package com.nkzy.controller;

import com.nkzy.pojo.Result;
import com.nkzy.pojo.Category;
import com.nkzy.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/categories")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @GetMapping("/{id}")
    public Result<Category> getCategoryById(@PathVariable Integer id) {
        Category category = categoryService.selectById(id);
        if (category != null) {
            return Result.success(category);
        } else {
            return Result.error("Category not found");
        }
    }

    @GetMapping
    public Result<List<Category>> getAllCategories() {
        List<Category> categories = categoryService.selectAll();
        return Result.success(categories);
    }

    @PostMapping
    public Result<Void> addCategory(@RequestBody Category category) {
        categoryService.insert(category);
        return Result.success(null);
    }

    @PutMapping
    public Result<Void> updateCategory(@RequestBody Category category) {
        categoryService.update(category);
        return Result.success(null);
    }

    @DeleteMapping("/{id}")
    public Result<Void> deleteCategory(@PathVariable Integer id) {
        categoryService.deleteById(id);
        return Result.success(null);
    }
}